package com.liam.socket.tcp;

import java.io.*;
import java.net.Socket;
import java.net.SocketAddress;

public class Task {

    public static class Output extends Thread {
        Socket socket;

        public Output(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try {
                while (true) {
                    OutputStream out = socket.getOutputStream();
                    PrintWriter writer = new PrintWriter(out);

                    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
                    String content = reader.readLine();

                    writer.println(content);
                    writer.flush();
                }
            } catch (Exception e) {
                e.printStackTrace();
                try {
                    socket.shutdownInput();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }



    public static class Input extends Thread {
        Socket socket;

        public Input(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try {
                while (true) {
                    InputStream in = socket.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));

                    String content;
                    while ((content = reader.readLine()) != null) {
                        SocketAddress remote = socket.getRemoteSocketAddress();
                        System.out.println(remote + ":" + content);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                try {
                    socket.shutdownInput();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
}
